package top.glkj.hms.security;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import top.glkj.hms.config.JwtConfig;
import top.glkj.hms.entity.User;
import top.glkj.hms.service.UserService;
import top.glkj.hms.utils.IpUtil;
import top.glkj.hms.utils.JwtTokenUtil;
import top.glkj.hms.utils.Result;
import top.glkj.hms.utils.ResultFactory;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author : xgl
 * @version : 0.0.1
 * @date :2020/11/28 1:50
 */
@Slf4j
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {
    private UserService userService;

    @Autowired
    public UserLoginSuccessHandler(UserService userService) {
        this.userService = userService;
    }

    /**
     * 登录成功返回结果
     *
     * @param request  请求
     * @param response 响应
     * @author xgl
     * @date 2020/11/14
     **/
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 组装JWT
        User user = (User) authentication.getPrincipal();
        Result one = userService.getOne(user.getId());

        if (!ResultFactory.isSuccess(one)) {
            response.setContentType("application/json;charset=UTF-8");
            ServletOutputStream out = response.getOutputStream();
            String str = JSONObject.toJSONString(one);
            out.write(str.getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        } else {
            user = (User) one.getObject();
            log.info(IpUtil.getIpAddress(request));
            user.setLastLoginClient(request.getHeader("User-Agent"));
            user.setLastLoginIp(IpUtil.getIpAddress(request));
            user.setLastLoginTime(new Date());
            user.setCount(user.getCount() <= 0 ? 1 : (user.getCount() + 1));
            String token = JwtTokenUtil.createAccessToken(user);
            token = JwtConfig.tokenPrefix + token;
            // 封装返回参数
            response.setContentType("application/json;charset=UTF-8");
            ServletOutputStream out = response.getOutputStream();
            String str = JSONObject.toJSONString(ResultFactory.isSuccess("登录成功", token));
            userService.save(user);
            out.write(str.getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        }


    }
}